import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class CurveFitGray extends FitnessFunction {
	int size;
	int[] testX;

	double[] testY;

	public CurveFitGray() throws NumberFormatException, IOException {
		name = "Curve Fitting Problem - Gray";

		// Create Table of X values from input file
		Scanner input = new Scanner(
				new FileReader(Parameters.dataInputFileName));
		size = input.nextInt();
		testX = new int[size];
		testY = new double[size];
		for (int i = 0; i < size; i++) {
			testX[i] = input.nextInt();
			testY[i] = input.nextDouble(); // changed by senglee - test data
											// could be float
		}
		input.close();
	}

	@Override
	public void doRawFitness(Chromo X) {
		double difference = 0;
		double esty = 0;
		
		if (X.getClass().getName().contains("ChromoGray")) {

			for (int z = 0; z < size; z++) {
				esty = (X.getIntGeneValue(0) * Math.pow(testX[z], 2))
						+ (X.getIntGeneValue(1) * testX[z])
						+ X.getIntGeneValue(2)
						+ (X.getIntGeneValue(3) * Math.sin(testX[z]))
						+ (X.getIntGeneValue(4) * Math.cos(testY[z]));

				// difference = Math.pow((testY[z] - esty), 2);
				difference = Math.abs(testY[z] - esty);
				// difference /= 1e4 ;

				X.rawFitness += difference;
			}

			X.rawFitness = X.rawFitness / size;
			X.rawFitness /= 1e4 ;
			
		}

	}

	@Override
	public void doPrintGenes(Chromo X, FileWriter output)
			throws java.io.IOException {

		for (int i = 0; i < Parameters.numGenes; i++) {
			Hwrite.right(X.getGeneAlpha(i), X.getGeneAlpha(i).length(), output);
		}

		output.write("\tGeneScore\t");
		for (int i = 0; i < Parameters.numGenes; i++) {
			String geneVal = Double.toString(X.getIntGeneValue(i));
			Hwrite.right(X.getIntGeneValue(i), geneVal.length(), output);
		}

		output.write("\tRawFitness\t ");
		String strRawFitness = Double.toString(X.rawFitness);
		Hwrite.right(X.rawFitness, strRawFitness.length(), output);
		output.write("\n\n");
		return;
	}
}
